package com.sgl.blog.controller.user;

import com.sgl.blog.pojo.BlogAccount;
import com.sgl.blog.pojo.Restful;
import com.sgl.blog.pojo.RestfulBuilder;
import com.sgl.blog.pojo.ResultCode;
import com.sgl.blog.service.AccountService;
import com.sgl.blog.service.MailService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

/**
 * @标题：
 * @内容：
 * @作者： 宋志豪
 */
@Slf4j
@Controller
@RequestMapping("user")
public class RegisterController {

    @Resource
    private AccountService accountService;

    @Resource
    private MailService mailService;


    /**
     * @return 转发到注册页
     */
    @GetMapping("register")
    public String registerPage(){
        return "register";
    }

    /**
     * 账号注册
     * @param account 账户传入信息
     * @return 返回到登入界面
     */
    @PostMapping("register")
    public String register(BlogAccount account){
        // 创建新账户
        accountService.newAccount(account);
        return "success";
    }

    /**
     * 发送验证码
     * @param account 账户传入信息
     * @return 返回到登入界面
     */
    @GetMapping("code")
    public @ResponseBody Restful<Map<String, Object>> code(BlogAccount account, HttpSession session){
        try {
            session.setAttribute("code", mailService.sendMail(account));
        } catch (MessagingException | UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return RestfulBuilder.successNoData(ResultCode.SUCCESS);
    }

    /**
     * 校验验证码
     * @param code 验证码
     * @return 返回到登入界面
     */
    @PostMapping("code")
    public @ResponseBody Restful<Map<String, Object>> code(String code,HttpSession session){
        log.info(code);
        if (session.getAttribute("code") != null){
            if (code.equals(session.getAttribute("code"))){
                session.removeAttribute("code");
                return RestfulBuilder.successNoData(ResultCode.SUCCESS);
            }
        }
        return RestfulBuilder.faile(ResultCode.DATA_IS_WRONG);
    }

    /**
     * 邮箱验证
     * @param account 账户传入信息
     * @return 返回到登入界面
     */
    @GetMapping("email")
    public @ResponseBody Restful<Map<String, Object>> email(BlogAccount account){
        Map<String, Object> data = new HashMap<>();
        data.put("available", !mailService.validationEmail(account));
        return RestfulBuilder.success(data, ResultCode.SUCCESS);
    }
}
